package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.D;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.SgAccount;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.bean.gen.TsAccountJournal;
import cn.jekun.component.core.bean.gen.TsAccountQuestion;
import cn.jekun.component.core.bean.gen.TsOperationCode;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.component.core.service.gen.TsAccountService;
import cn.jekun.shop.web.bean.ShopAccounts;

/**
 * 账户流水查询Service
 * @author yuan
 *
 */
@Service(AccountService.BEAN_NAME)
public class AccountService extends ShopBaseService{
	public static final String BEAN_NAME="cn.jekun.shop.common.service.AccountService";
	@Override
	public String getNamespace() {
		// TODO Auto-generated method stub
		return "ACTION_TS_ACCOUNT_DETAILS";
	}
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;
	
	@Resource(name = TsAccountService.BEAN_NAME)
	TsAccountService tsAccountService;

//	/**
//	 * 获取余额
//	 * @param ShopId
//	 * @return
//	 */
//	public double[] getBalance(@ErpShop.AnnoShopId @NotBlank(message="商家编码不能为空") String ShopId){
//		try {
//			return accountDao.getShopBalance(ShopId);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

	/**
	 * 获取账户流水明细
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public JSONObject getAccountDetails(@Num(length = 1) String queryDate,
												@TsAccountJournal.AnnoOperationCode String operType,
												@Num(length = 10,scale=2,message="请输入正确的金额") String beginMoney,
												@Num(length = 10,scale=2,message="请输入正确的金额") String endMoney,
												@Security String keyRange,
												@D String beginDate,
												@D String endDate,
												@Security String keyword_s,
												@RsUser.AnnoUserId String userId,
												String pageSize,
												@Security
												String currentPage){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(currentPage)) {
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		
		String SQL ="";
		if(queryDate!=null && queryDate.toString().length()>0){
			if("1".equals(queryDate)){ 
				SQL +=" and trunc(a.CREATE_TIME) = trunc(sysdate)";  //今天的数据
			}else if("2".equals(queryDate)){
				SQL +=" and trunc(a.create_time) >= trunc(add_months(sysdate,-1))"; //最近一个月的数据
			}else if(queryDate!=null && "3".equals(queryDate)){
				SQL +=" and trunc(a.create_time) >= trunc(add_months(sysdate,-3))";  //3个月的数据
			}else if("4".equals(queryDate)){
				SQL +=" and trunc(a.create_time) >= trunc(add_months(sysdate,-12))"; //1年的数据
			}else if("5".equals(queryDate)){ //1年前的数据
				SQL +=" and trunc(a.create_time) <= trunc(add_months(sysdate,-12))";	
			}
		}if(operType!=null && operType.toString().length()>0){
			SQL +=" and a.OPERATION_CODE = '"+operType.toString()+"'"; 
		}if(!"".equals(beginMoney) && "".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney; 
		}if("".equals(beginMoney) && !"".equals(endMoney)){
			SQL +=" and a.amount<="+endMoney; 
		}if(beginMoney!=null && endMoney!=null && !"".equals(beginMoney) 
				&& !"".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney+" and a.amount<="+endMoney+""; 
		}
		if("".equals(beginDate) && !"".equals(endDate)){
			SQL +=" and a.create_time"
					+ "<= to_date('"+endDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && "".equals(endDate)){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && beginDate!=null 
				&& !"".equals(endDate) && endDate!=null){
			SQL +=" and a.create_time >= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')"
					+ " and a.create_time <= to_date('"+endDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')"; 
		}
		if(keyRange!=null && keyword_s.toString().length()>0 ){
			if("bill".equals(keyRange)){
				SQL +=" and a.account_journal_id like '%"+keyword_s.toString()+"%'"; 	
			}else if("name".equals(keyRange)){
				SQL +=" and e.operation like '%"+keyword_s.toString()+"%'"; 
			}

		}
		System.out.println("SQL="+SQL);
		Map formMap=new HashMap<String, String>();
		formMap.put("userId", userId);
		SqlUtis.prepareSql(formMap,SQL);
		JSONArray jsonArray = JSONArray.fromObject(this.list(this.getStatementName("list"),formMap,page));
		jsonObject.put("accountListData", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		jsonObject.put("pages", page.getPages());
		jsonObject.put("pageSize", page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		
		return executeRerutn(jsonObject);


	}
	
	
	/**
	 * 获取账户流水明细
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public TsAccount one(@RsUser.AnnoUserId String userId){
		Map map=new HashMap<String, String>();
		map.put("userId", userId);
		return this.one(this.getStatementName("query"),map);


	}

	/**
	 * 获取账户流水类型
	 * @return
	 */
	public List<TsOperationCode> getOperTypes(){

		return this.list(this.getStatementName("queryoperationcode"),null);
	}

	/**
	 * 获取日期条件
	 * @return
	 * @deprecated 这什么东西？
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<ShopAccounts> getQueryDate(@Num(length = 1)String queryDate){
		String SQL ="";
		Map map=new HashMap<String, String>();
		if(queryDate!=null && queryDate.toString().length()>0){
			if("1".equals(queryDate)){ 
				SQL +=" to_char(sysdate,'yyyy-MM-dd') beginDate,to_char(sysdate,'yyyy-MM-dd') endDate";  //今天
			}else if("2".equals(queryDate)){
				SQL +="to_char(add_months(sysdate,-1),'yyyy-MM-dd') beginDate, to_char(sysdate,'yyyy-MM-dd') endDate"; //最近一个月
			}else if(queryDate!=null && "3".equals(queryDate)){
				SQL +="to_char(add_months(sysdate,-3),'yyyy-MM-dd') beginDate, to_char(sysdate,'yyyy-MM-dd') endDate";  //3个月
			}else if("4".equals(queryDate)){
				SQL +="to_char(add_months(sysdate,-12),'yyyy-MM-dd') beginDate,to_char(sysdate,'yyyy-MM-dd') endDate"; //1年
			}else if("5".equals(queryDate)){ //1年前
				SQL +="to_char(add_months(sysdate,-12),'yyyy-MM-dd') endDate";	
			}
			map.put("COLUMN_SQL", SQL);
			return this.list(this.getStatementName("getQueryDate"),map);
		}else{
			SQL += "to_char(min(create_time),'yyyy-MM-dd') beginDate,to_char(max(create_time),'yyyy-MM-dd') endDate";
			map.put("COLUMN_SQL", SQL);
			return this.list(this.getStatementName("getQueryDate2"),map);
		}

	}
	
	/**
	 * 获取账户提现详情
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public ShopAccounts  getAccountDetailsById( @NotBlank(message="流水编码不能为空") @TsAccountJournal.AnnoAccountJournalId String accountJourId){
		Map map=new HashMap<String, String>();
		map.put("accountJourId", accountJourId);
		return this.one(this.getStatementName("getAccountsDetailsById"),map);
	}
	
	/**
	 * 获取当天提现的次数
	 * @param accountId
	 * @return
	 */
	public int getSettleTimes(@NotBlank(message="账户代码不能为空")@SgAccount.AnnoAccountId String accountId){
		Map map = new HashMap();
		map.put(SgAccount.COL_ACCOUNT_ID, accountId);
		return this.count(this.getStatementName("getSettleTimes"),map);
	}
	
	public HashMap getTsAccount(@RsUser.AnnoUserId String userId,String ownerTypeId){
    	Map formMap = null;
    	formMap = new HashMap();
        formMap.put(TsAccount.COL_OWNER_ID,userId);
        formMap.put(TsAccount.COL_OWNER_TYPE_ID, ownerTypeId);
        formMap.put(TsAccount.COL_ACCOUNT_TYPE_ID, "1");
		SqlUtis.prepareSql(formMap, "",
				SqlUtis.getSQLRequired(formMap, "a."+TsAccount.COL_OWNER_TYPE_ID, Types.VARCHAR),
				SqlUtis.getSQLRequired(formMap, "a."+TsAccount.COL_ACCOUNT_TYPE_ID, Types.VARCHAR),
				SqlUtis.getSQLRequired(formMap, "a."+TsAccount.COL_OWNER_ID, Types.VARCHAR));
		return this.one(this.getStatementName("getAccount"),formMap);
    }
	
	/**
	 * 获取密保问题列表-账户安全
	 * @param map
	 * @return
	 */
	public JSONObject getAccountQuestions(String type){
		JSONObject jsonObject = new JSONObject();
		Map map=new HashMap<String, String>();
		map.put(TsAccountQuestion.COL_TYPE, type);
		
		SqlUtis.prepareSql(map, "",
				SqlUtis.getSQLRequired(map, TsAccountQuestion.COL_TYPE, Types.VARCHAR));
		
		JSONArray jsonArray = JSONArray.fromObject(this.list("TS_ACCOUNT_QUESTION.list",map));
		jsonObject.put("questionListData", jsonArray);
		
		return executeRerutn(jsonObject);

	}
	
	/**
	 * 设置支付密码
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean addPayPwd(@TsAccount.AnnoOwnerId String ownerId,
								@TsAccount.AnnoOwnerTypeId String ownerTypeId,
							   	String password,
							   	@TsAccount.AnnoQuestionId String questionId,
							   	@TsAccount.AnnoAnswer String answer){
		Map map = new HashMap();
		
		TsAccount tsAccount= accountPayService.getAccountInfo(ownerId,ownerTypeId);
		if(tsAccount!=null){
			
			TsAccount updateTsAccount = new TsAccount();
			updateTsAccount.setAccountId(tsAccount.getAccountId());
			updateTsAccount.setPassword(password);
			updateTsAccount.setQuestionId(questionId);
			updateTsAccount.setAnswer(answer);
			//BOX-527 设置了支付密码，备付金账户仍未激活。
			if (tsAccount.getStatusId() == null || Constants.TS_ACCOUNT_STATUS.STATUS_05.equals(tsAccount.getStatusId())) {
				updateTsAccount.setStatusId(Constants.TS_ACCOUNT_STATUS.STATUS_00);//账户状态
			}
			
			tsAccountService.update(updateTsAccount);
			
		}else{
			tsAccount=new TsAccount();
			//初使化账户信息TsAccount
			tsAccount.setAccountTypeId(Constants.TS_ACCOUNT_TYPE.PAYMENT);//账户类型：1支付账户，2结算账户，现在统一为支付账户
			tsAccount.setBalance(new Double(0.00));//账户金额，创建账户时为0
			tsAccount.setFrozenAmount(new Double(0.00));//冻结金额
			tsAccount.setOwnerId(ownerId);//根据ownertype，分别对应所属的ID号
			tsAccount.setOwnerTypeId(ownerTypeId);//户主类型，1商家，2代理商，0普通用户
			tsAccount.setPassword(password);//账 户密码，采用MD5加密后的内容
			tsAccount.setSignType(Constants.TS_ACCOUNT_SIGN_TYPE.SIGN_TYPE_01);//加密类型，默认为MD5
			tsAccount.setStatusId(Constants.TS_ACCOUNT_STATUS.STATUS_00);//账户状态：00正常，01：冻结，02销户，03挂失，04锁定,05未激活
			tsAccount.setMemo("");//备注
			tsAccount.setQuestionId(questionId);
			tsAccount.setAnswer(answer);
			
			tsAccountService.insert(tsAccount);
		}
		
		return true;
	}
	
	/**
	 * 修改支付密码
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public JSONObject editPayPwd(@TsAccount.AnnoOwnerId String ownerId,
								@TsAccount.AnnoOwnerTypeId String ownerTypeId,
							   	String password,
							   	String newpassword,
							   	@TsAccount.AnnoQuestionId String questionId,
							   	@TsAccount.AnnoAnswer String answer){
		Map map = new HashMap();
		JSONObject jsonObject=new JSONObject();
		
		TsAccount tsAccount= accountPayService.getAccountInfo(ownerId,ownerTypeId);
		
		if(tsAccount!=null){
			if(!tsAccount.getPassword().equals(password)){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"原密码不正确");
				return jsonObject;
			}
			
			if(!tsAccount.getQuestionId().equals(questionId)){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"密保问题不正确");
				return jsonObject;
			}

			if(!tsAccount.getAnswer().equals(answer)){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"密保答案不正确");
				return jsonObject;
			}
			
			tsAccount.setPassword(newpassword);
			
			tsAccountService.update(tsAccount);
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"修改支付密码成功");
		}else{
			
		}
		
		return jsonObject;
	}
	
	/**
	 * 是否设置过支付密码
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean isAddPayPwd(@TsAccount.AnnoOwnerId String ownerId,
								@TsAccount.AnnoOwnerTypeId String ownerTypeId){
		Map map = new HashMap();
		
		TsAccount tsAccount= accountPayService.getAccountInfo(ownerId,ownerTypeId);
		if(tsAccount!=null){
			if(tsAccount.getPassword().equals("password") || tsAccount.getPassword().equals("")){//自动生成的账户
				return false;
			}
			if(tsAccount.getQuestionId() == null || tsAccount.getQuestionId().equals("")){
				return false;
			}
			if(tsAccount.getAnswer() == null || tsAccount.getAnswer().equals("")){
				return false;
			}
			
		}else{
			return false;
		}
		
		return true;
	}
}
